package test.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOutboundHandlerAdapter;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.ChannelPromise;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.Charset;
import java.util.Scanner;
@Slf4j
public class NettyServer {
    public static void main(String[] args) throws InterruptedException {
        final NioEventLoopGroup bossGroup = new NioEventLoopGroup(1);
        final NioEventLoopGroup workerGroup = new NioEventLoopGroup(2);

        try {
            Channel channel = new ServerBootstrap()
                    .group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<NioSocketChannel>() { // 修改为 NioSocketChannel
                        @Override
                        protected void initChannel(NioSocketChannel ch) throws Exception {
                            ChannelPipeline pipeline = ch.pipeline();
                            pipeline.addLast(new ChannelInboundHandlerAdapter() {
                                @Override
                                public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                    if (msg instanceof ByteBuf) {
                                        ByteBuf byteBuf = (ByteBuf) msg;
                                        String string = byteBuf.toString(Charset.defaultCharset());
                                        log.debug("收到消息：{}", string);
                                        byteBuf.release(); // 释放 ByteBuf
                                    }
                                }
                            });

                            pipeline.addLast(new ChannelOutboundHandlerAdapter() {
                                @Override
                                public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
                                    log.debug("准备发送消息到客户端：{}", msg);
                                    super.write(ctx, msg, promise); // 确保将消息写到通道
                                }
                            });
                        }
                    }).bind(8080).sync() // 确保同步
                    .channel();

            new Thread(() -> {
                Scanner scanner = new Scanner(System.in);
                while (true) {
                    String line = scanner.nextLine();
                    if ("q".equals(line)) {
                        channel.close();
                        break;
                    }
                    // 这里需要维护对客户端通道的引用
                    // 假设有一些方法可以得到当前已连接的客户端通道
                    // For instance: Channel clientChannel = getClientChannel();
                    // clientChannel.writeAndFlush(Unpooled.copiedBuffer("服务器发送消息: " + line, Charset.defaultCharset()));
                }
            }, "input").start();

            // 等待通道关闭
            channel.closeFuture().sync();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}
